﻿using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

using System.Threading;
using System.Globalization;

using System.Collections;
using CE.Database;
using CE.Configuration;

/// <summary>
/// Summary description for General
/// </summary>
/// 
namespace CE.Global
{
    public class General
    {

        public static string UserTypeId = "UserTypeId";
        public static string UserEmail = "UserEmail";
        public static string UserPhoneNo = "UserPhone";
        public static string UserName = "UserName";

        public static string UserId = "UserId";
        public static string UserProfileAndContactComplete = "IsProfileContactComplete";
        public static string UserICNumber = "UserICNumber";

        public static string RequestUrl = "RequestUrl";
        public static string StartTime = "StartTime";
        public static string Guest = "Guest";
        public static string LoginHistoryId = "LoginHistoryId";
        public static string LastLoginTime = "LastLoginTime";
        public static string SecurityCheckWord = "Salt";
        public static string IsAcceptTC = "IsAcceptTC";

        //Car Insurance Session
        public static string CarServiceName = "Car Insurance";
        public static string CarId = "CarId";
        public static string CarPolicyId = "CarPolicyId";
        public static string CarResultId = "CarResultId";
        public static string IsCarRestoreResult = "IsCarRestoreResult";
        public static string CarMoreDetailId = "CarMoreDetailId";
        public static string CarClaimHistoryId = "CarClaimHistoryId";
        public static string CvvId = "CvvId";
        public static string IsCarDetailChange = "IsCarDetailChange";
        public static string OrderRefNo = "OrderRefNo";
        public static string InquiryId = "InquiryId";

        //View Details ID
        public static string ViewedDetailsId = "ViwedDetailsId";

        //DownLoad Proposal
        public static string RefId = "RefId";
        public static string InsType = "InsType";

        //Agent
        public static string AgentId = "AgentId";
        public static string AgentName = "AgentName";
        public static string AgentBuyOnly = "AgentBuyOnly";


        public General()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static DataTable GetComboItem(string keyName, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " Where [Status] = 1 ";
                    _sqlstatement += _sqlwhere;
                }

                _sqlstatement += " Order By " + _keyValueList[1];
                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }

        public static DataTable GetComboItem(string keyName, string OrderBy, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " Where [Status] = 1 ";
                    _sqlstatement += _sqlwhere;
                }

                if (OrderBy != "")
                {
                    _sqlstatement += " Order by " + OrderBy;
                }

                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }

        public static DataTable GetComboItem(string keyName, string whereKey, string whereId, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                _sqlstatement += " WHERE " + whereKey + " = " + whereId;
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " AND [Status] = 1;";
                    _sqlstatement += _sqlwhere;
                }

                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }

        public static DataTable GetComboItem(string keyName, string whereKey1, string whereId1, string whereKey2, string whereId2, bool status)
        {
            DataTable _dt = null;
            try
            {
                MyDatabase _db = new MyDatabase();

                string _keyValue = MyConfigurationManager.GetAppSettingValue(keyName);
                string[] _keyValueList = _keyValue.Split(',');

                string _sqlstatement = "SELECT " + _keyValueList[2] + ", " + _keyValueList[1] + " FROM " + _keyValueList[0];
                _sqlstatement += " WHERE " + whereKey1 + " = " + whereId1 + "  AND " + whereKey2 + " = " + whereId2;
                string _sqlwhere = "";

                if (status)
                {
                    _sqlwhere = " AND [Status] = 1;";
                    _sqlstatement += _sqlwhere;
                }

                _dt = _db.GetDataTable(_sqlstatement);
            }
            catch (Exception Ex)
            {
            }

            return _dt;
        }

        public static String SetCulture()
        {
            String selectedCulture = string.Empty;
            if (HttpContext.Current.Session["Language"] != null)
            {
                selectedCulture = HttpContext.Current.Session["Language"].ToString();
            }
            else
            {
                //selectedCulture = "th-TH";
                selectedCulture = ((System.Web.Configuration.GlobalizationSection)(System.Configuration.ConfigurationSettings.GetConfig("system.web/globalization"))).UICulture;
                HttpContext.Current.Session["Language"] = selectedCulture;
            }

            //UICulture = selectedCulture;
            //Culture = selectedCulture;

            //Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedCulture);

            return selectedCulture;
        }

        public static void CreateUpdateUserLoginCached(System.Web.UI.Page thisPage)
        {
            string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.TH.UserCacheName");
            sKey += Convert.ToString(thisPage.Session[UserId].ToString());
            // Accessing the Cache Item extends the Sliding Expiration automatically
            //thisPage.Cache.Remove(sKey);
            if (thisPage.Cache[sKey] != null)
            {
                string sUser = thisPage.Cache[sKey].ToString();
            }
            else
            {
                TimeSpan SessTimeOut = new TimeSpan(0, 0, thisPage.Session.Timeout, 0, 0);
                thisPage.Cache.Insert(sKey, thisPage.Session[UserId].ToString(), null, DateTime.MaxValue, SessTimeOut,
                   System.Web.Caching.CacheItemPriority.NotRemovable, null);
            }
        }

        public static bool CheckAllLowerCase(string inputString)
        {
            const string ALL_CAPS_PATTERN = "[A-Z]";
            Regex All_Caps_Regex = new Regex(ALL_CAPS_PATTERN);
            if (All_Caps_Regex.IsMatch(inputString))
            {
                return false;
            }
            return true;
        }

        public static void ClearAllSession(System.Web.UI.Page PageSession, string strExceptType)
        {
            #region Comment
            //string strUserId = string.Empty;
            //string strUserTypeId = string.Empty;
            //string strUserEmail = string.Empty;
            //string strUserPhoneNo = string.Empty;
            //string strUserName = string.Empty;

            //if (PageSession.Session[UserId] != null) strUserId = PageSession.Session[UserId].ToString();
            //if (PageSession.Session[UserTypeId] != null) strUserId = PageSession.Session[UserTypeId].ToString();
            //if (PageSession.Session[UserEmail] != null) strUserId = PageSession.Session[UserEmail].ToString();
            //if (PageSession.Session[UserPhoneNo] != null) strUserId = PageSession.Session[UserPhoneNo].ToString();
            //if (PageSession.Session[UserName] != null) strUserId = PageSession.Session[UserName].ToString();

            //PageSession.Session.Clear();
            //PageSession.Session.Abandon();

            //PageSession.Session[UserId] = strUserId;
            //PageSession.Session[UserTypeId] = strUserTypeId;
            //PageSession.Session[UserEmail] = strUserEmail;
            //PageSession.Session[UserPhoneNo] = strUserPhoneNo;
            //PageSession.Session[UserName] = strUserName;

            //PageSession.Session["UserId"] = "UserId";
            //PageSession.Session["UserTypeId"] = "UserTypeId";
            //PageSession.Session["UserEmail"] = "UserEmail";
            //PageSession.Session["UserPhoneNo"] = "UserPhone";
            //PageSession.Session["UserName"] = "UserName";
            //PageSession.Session["UserICNumber"] = "UserICNumber";
            //PageSession.Session["RequestUrl"] = "RequestUrl";
            //PageSession.Session["StartTime"] = "StartTime";
            //PageSession.Session["Guest"] = "Guest";
            //PageSession.Session["LoginHistoryId"] = "LoginHistoryId";
            //Car Insurance Session
            #endregion

            PageSession.Session["salt"] = null;
            PageSession.Session["ImageCount"] = null;

            if (strExceptType == "CI")
            {
                PageSession.Session[CarId] = null;
                PageSession.Session[CarPolicyId] = null;
                PageSession.Session[CarResultId] = null;
                PageSession.Session[CarMoreDetailId] = null;
                PageSession.Session[CarClaimHistoryId] = null;
                PageSession.Session[CvvId] = null;
                PageSession.Session[IsCarRestoreResult] = null;
                PageSession.Session[OrderRefNo] = null;
                PageSession.Session[InquiryId] = null;

            }

            if (strExceptType == "LOGOUT")
            {
                ClearUserLoginCached(PageSession);
                PageSession.Session[UserId] = null;
                PageSession.Session[UserTypeId] = null;
                PageSession.Session[UserEmail] = null;
                PageSession.Session[UserPhoneNo] = null;
                PageSession.Session[UserName] = null;
                PageSession.Session[IsAcceptTC] = null;

                PageSession.Session[UserICNumber] = null;
                PageSession.Session[RequestUrl] = null;
                PageSession.Session[StartTime] = null;
                //PageSession.Session["Guest"] = null;
                PageSession.Session[LoginHistoryId] = null;
                PageSession.Session[LastLoginTime] = null;
                //PageSession.Session[ProviderCompanyId] = null;
                PageSession.Session[UserProfileAndContactComplete] = null;
                //PageSession.Session[ProviderUserTypeId] = null;
                //PageSession.Session[ProviderUserAccessLevel] = null;

                PageSession.Session[AgentId] = null;
                PageSession.Session[AgentName] = null;
                PageSession.Session[AgentBuyOnly] = null;

            }
        }

        public static bool ClearUserLoginCached(System.Web.UI.Page thisPage)
        {
            bool _retValue = false;
            string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.UserCacheName");
            sKey += thisPage.Session[UserId].ToString();

            if (thisPage.Cache[sKey] == null)
            {
                _retValue = true;
            }
            else
            {
                thisPage.Cache.Remove(sKey);
                _retValue = true;
            }

            return _retValue;
        }

        public static string GetProviderCompanyLogo(string providerid)
        {
            string logourl = "/images/results/";
            if (providerid == "11")
            {
                logourl += "allianz.jpg";
            }
            else if (providerid == "12")
            {
                logourl += "msig.jpg";
            }
            else if (providerid == "16")
            {
                logourl += "axa.jpg";
            }
            else if (providerid == "29")
            {
                logourl += "lmg.jpg";
            }
            else if (providerid == "31")
            {
                logourl += "aig.jpg";
            }
            else if (providerid == "32")
            {
                logourl += "bki.jpg";
            }
            else if (providerid == "33")
            {
                logourl += "muangthai.jpg";
            }
            else if (providerid == "35")
            {
                logourl += "krungthai.jpg";
            }
            else if (providerid == "39")
            {
                logourl += "mittare.jpg";
            }
            else if (providerid == "41")
            {
                logourl += "ksk.jpg";
            }
            else if (providerid == "43")
            {
                logourl += "synmunkong.jpg";
            }
            else if (providerid == "45")
            {
                logourl += "viriyah.jpg";
            }
            else if (providerid == "46")
            {
                logourl += "tokiomarine.jpg";
            }
            else if (providerid == "50" || providerid == "51")
            {
                logourl += "scb.jpg";
            }
            else if (providerid == "58")
            {
                logourl += "thaivivat.jpg";
            }
            else if (providerid == "65")
            {
                logourl += "dhipaya.jpg";
            }
            else if (providerid == "66")
            {
                logourl += "thaipaiboon.jpg";
            }
            else if (providerid == "67")
            {
                logourl += "deves.jpg";

            }
            else if (providerid == "68")
            {
                logourl += "thaisri.jpg";

            }
            else if (providerid == "69")
            {
                logourl += "asset.jpg";

            }

            return logourl;
        }

        public static string GetRefNumber(Int64 FirstId)
        {
            string _vallasttwo = "";
            string _valfirstchar = "";
            string _valsecondchar = "";
            string _valremaining = "";
            string _result = "";
            Int64 _firstId = FirstId;
            if (_firstId.ToString().Length >= 2)
            {
                _valremaining = _firstId.ToString().Substring(0, _firstId.ToString().Length - 2);
                _vallasttwo = _firstId.ToString().Substring(_firstId.ToString().Length - 2, 2);
                _valfirstchar = _vallasttwo.Substring(0, 1);
                _valsecondchar = _vallasttwo.Substring(1, 1);
                _valfirstchar = NumberToChar(Convert.ToInt32(_valfirstchar));
                _valsecondchar = NumberToChar(Convert.ToInt32(_valsecondchar));
                _result = _valremaining + "" + _valfirstchar + "" + _valsecondchar;
            }
            else if (_firstId.ToString().Length == 1)
            {
                _valfirstchar = _firstId.ToString();
                _valfirstchar = NumberToChar(Convert.ToInt32(_valfirstchar));
                _result = _valfirstchar;
            }

            return _result;
        }

        public static string NumberToChar(int id)
        {
            string C = "";
            if (id == 1)
                C = "A";
            else if (id == 2)
                C = "B";
            else if (id == 3)
                C = "C";
            else if (id == 4)
                C = "D";
            else if (id == 5)
                C = "E";
            else if (id == 6)
                C = "F";
            else if (id == 7)
                C = "G";
            else if (id == 8)
                C = "H";
            else if (id == 9)
                C = "I";
            else if (id == 0)
                C = "J";
            return C;
        }

        public static string GetReferenceNumber(string Number, string ProviderId, string PackageName)
        {
            string convertno = CE.Global.General.GetRefNumber(Convert.ToInt64(Number.ToString()));
            string _RefNo = "";
            if (PackageName != "GluayGluay.com Special")
            {
                if (ProviderId == "11")
                {
                    _RefNo = "AZC" + convertno.ToString();
                }
                else if (ProviderId == "12")
                {
                    _RefNo = "MSI" + convertno.ToString();
                }
                else if (ProviderId == "16")
                {
                    _RefNo = "AXA" + convertno.ToString();
                }
                else if (ProviderId == "29")
                {
                    _RefNo = "LMG" + convertno.ToString();
                }
                else if (ProviderId == "31")
                {
                    _RefNo = "CTS" + convertno.ToString();
                }
                else if (ProviderId == "32")
                {
                    _RefNo = "BKI" + convertno.ToString();
                }
                else if (ProviderId == "33")
                {
                    _RefNo = "MTI" + convertno.ToString();
                }
                else if (ProviderId == "35")
                {
                    _RefNo = "KPI" + convertno.ToString();
                }
                else if (ProviderId == "39")
                {
                    _RefNo = "MIR" + convertno.ToString();
                }
                else if (ProviderId == "41")
                {
                    //_RefNo = "KUR" + convertno.ToString();
                    _RefNo = "KSK" + convertno.ToString();
                }
                else if (ProviderId == "43")
                {
                    _RefNo = "SMK" + convertno.ToString();
                }
                else if (ProviderId == "45")
                {
                    _RefNo = "VRY" + convertno.ToString();
                }
                else if (ProviderId == "46")
                {
                    _RefNo = "TMS" + convertno.ToString();
                }
                else if (ProviderId == "50" || ProviderId == "51")
                {
                    _RefNo = "SCS" + convertno.ToString();
                }
                else if (ProviderId == "58")
                {
                    _RefNo = "TVV" + convertno.ToString();
                }
                else if (ProviderId == "65")
                {
                    _RefNo = "DPY" + convertno.ToString();
                }
                else if (ProviderId == "66")
                {
                    _RefNo = "TPB" + convertno.ToString();
                }
                else if (ProviderId == "67")
                {
                    _RefNo = "DVS" + convertno.ToString();
                }
                else if (ProviderId == "68")
                {
                    _RefNo = "THI" + convertno.ToString();
                }
                else if (ProviderId == "69")
                {
                    _RefNo = "ASE" + convertno.ToString();
                }
            }
            else
            {
                _RefNo = "GG" + ProviderId.ToString() + convertno.ToString();
            }
            return _RefNo;
        }

        public static string GetProviderName(Int64 ProviderCompanyId, string Language)
        {
            string _result = "";
            if (Language == "1")
            {
                if (ProviderCompanyId == 11)
                {
                    _result = "อลิอันซ์ ซี.พี. ประกันภัย";
                }
                else if (ProviderCompanyId == 12)
                {
                    _result = "เอ็ม เอส ไอ จี ประกันภัย";
                }
                else if (ProviderCompanyId == 16)
                {
                    _result = "แอกซ่า ประกันภัย";
                }
                else if (ProviderCompanyId == 29)
                {
                    _result = "แอลเอ็มจี ประกันภัย";
                }
                else if (ProviderCompanyId == 31)
                {
                    _result = "นิวแฮมพ์เชอร์ อินชัวรันส์";
                }
                else if (ProviderCompanyId == 32)
                {
                    _result = "กรุงเทพประกันภัย";
                }
                else if (ProviderCompanyId == 33)
                {
                    _result = "เมืองไทยประกันภัย";
                }
                else if (ProviderCompanyId == 35)
                {
                    _result = "กรุงไทยพานิชประกันภัย";
                }
                else if (ProviderCompanyId == 39)
                {
                    _result = "มิตรแท้ประกันภัย";
                }
                else if (ProviderCompanyId == 41)
                {
                    _result = "เค เอส เค";// "คูเนีย ประกันภัย";
                }
                else if (ProviderCompanyId == 43)
                {
                    _result = "สินมั่นคงประกันภัย";
                }
                else if (ProviderCompanyId == 45)
                {
                    _result = "วิริยะประกันภัย";
                }
                else if (ProviderCompanyId == 46)
                {
                    _result = "โตเกียวมารีนศรีเมือง";
                }
                else if (ProviderCompanyId == 50)
                {
                    _result = "ไทยพาณิชย์สามัคคีประกันภัย";
                }
                else if (ProviderCompanyId == 58)
                {
                    _result = "ประกันภัยไทยวิวัฒน์";
                }

            }
            else if (Language == "2")
            {
                if (ProviderCompanyId == 11)
                {
                    _result = "Allianz CP Insurance";
                }
                else if (ProviderCompanyId == 12)
                {
                    _result = "MSIG Insurance";
                }
                else if (ProviderCompanyId == 16)
                {
                    _result = "AXA Insurance";
                }
                else if (ProviderCompanyId == 29)
                {
                    _result = "LMG  Insurance";
                }
                else if (ProviderCompanyId == 31)
                {
                    _result = "Chartis Insurance";
                }
                else if (ProviderCompanyId == 32)
                {
                    _result = "BKI Insurance";
                }
                else if (ProviderCompanyId == 33)
                {
                    _result = "MuangThai Insurance";
                }
                else if (ProviderCompanyId == 35)
                {
                    _result = "KrungThai Insurance";
                }
                else if (ProviderCompanyId == 39)
                {
                    _result = "Mittare Insurance";
                }
                else if (ProviderCompanyId == 41)
                {
                    _result = "KSK Insurance";
                }
                else if (ProviderCompanyId == 43)
                {
                    _result = "Synmunkong Insurance";
                }
                else if (ProviderCompanyId == 45)
                {
                    _result = "Viriyah Insurance";
                }
                else if (ProviderCompanyId == 46)
                {
                    _result = "Tokio Marine Insurance";
                }
                else if (ProviderCompanyId == 50)
                {
                    _result = "SCSMG Insurance";
                }
                else if (ProviderCompanyId == 58)
                {
                    _result = "Thaivivat Insurance";
                }
            }
            return _result;
        }

        public static bool isMobileBrowser()
        {
            //GETS THE CURRENT USER CONTEXT
            HttpContext context = HttpContext.Current;

            //FIRST TRY BUILT IN ASP.NT CHECK
            if (context.Request.Browser.IsMobileDevice)
            {
                return true;
            }
            //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
            if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
            {
                return true;
            }
            //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
            if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
                context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
            {
                return true;
            }
            //AND FINALLY CHECK THE HTTP_USER_AGENT 
            //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
            if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
            {
                //Create a list of all mobile types
                string[] mobiles = new string[] {
                    "midp", "j2me", "avant", "docomo", 
                    "novarra", "palmos", "palmsource", 
                    "240x320", "opwv", "chtml",
                    "pda", "windows ce", "mmp/", 
                    "blackberry", "mib/", "symbian", 
                    "wireless", "nokia", "hand", "mobi",
                    "phone", "cdm", "up.b", "audio", 
                    "SIE-", "SEC-", "samsung", "HTC", 
                    "mot-", "mitsu", "sagem", "sony"
                    , "alcatel", "lg", "eric", "vx", 
                    "NEC", "philips", "mmm", "xx", 
                    "panasonic", "sharp", "wap", "sch",
                    "rover", "pocket", "benq", "java", 
                    "pt", "pg", "vox", "amoi", 
                    "bird", "compal", "kg", "voda",
                    "sany", "kdd", "dbt", "sendo", 
                    "sgh", "gradi", "jb", "dddi", 
                    "moto", "iphone"
                };

                //Loop through each item in the list created above 
                //and check if the header contains that text
                foreach (string s in mobiles)
                {
                    if (context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower()))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
        
        public static DateTime GetUTCDateTime()
        {
            DateTime _CurrentDateTime = DateTime.UtcNow.AddHours(7);
            return _CurrentDateTime;
        }
        
        public static DateTime GetUTCDateTimeToday()
        {
            DateTime _CurrentDateTime = DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc);
            return _CurrentDateTime;
        }

        public enum CEUserType
        {
            SiteAdmin = 100,
            SiteUser = 200,
            Provider = 300,
            Customer = 400,
            Advertiser = 500,
            Guest = 600
        }
    }
}